package prototypePatter1;

import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 浅拷贝
 * @Date: Created in 2021/12/17 10:47
 */
@ToString
public class ShallowClone implements Cloneable {
    private int age;
    private List<String> list = new ArrayList<>();

    public ShallowClone() {
    }

    public ShallowClone(int age, List<String> list) {
        this.age = age;
        this.list = list;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(String str) {
        this.list.add(str);
    }

    @Override
    protected ShallowClone clone() throws CloneNotSupportedException {
        return (ShallowClone) super.clone();
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        // 为shallowClone赋值
        ShallowClone shallowClone = new ShallowClone();
        shallowClone.setAge(12);
        shallowClone.setList("123");

        // clone后对新对象进行赋值
        ShallowClone clone = shallowClone.clone();
        // 如果新对象不设置age属性，age还是12
        clone.setAge(11);
        // 因为对引用类型是不进行拷贝，所以对list的两次添加数据会保存在一起
        clone.setList("456");

        // ShallowClone(age=12, list=[123, 456])
        System.out.println(shallowClone.toString());
        // ShallowClone(age=11, list=[123, 456])
        System.out.println(clone.toString());
    }
}
